import Vue from 'vue'
import Vuex from 'vuex'
import Crypto from '@/assets/js/crypto'
Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    token: '',
    mac: '',
    websocket: ''
  },
  mutations: {
    setToken(state, payload) {
      state.token = payload
    },
    setMac(state, payload) {
      state.mac = payload
    },
    setWebSocket(state, payload) {
      state.websocket = payload
    }
  },
  actions: {
    connectWebSocket({ commit, dispatch }) {
      const interfaces = window.require('os').networkInterfaces()
      var websocket = new WebSocket(`ws://192.168.0.107:8080/ws/${interfaces.WLAN[1].mac}`)
      commit('setWebSocket', websocket)
      websocket.onopen = function() {
        console.log('websocket open')
      }
      // WebSocket断开回调
      websocket.onclose = function() {
        console.log('websocket close')
      }
      // WebSocket接收回调，只接收字符串参数，所以在服务端相传对象过来可以用JSON先转换成字符串，然后在这边转成对象
      websocket.onmessage = function(e) {
        dispatch('getWebSocketMsg', e)
      }
    },
    getWebSocketMsg(e, msg) {
      // encryptByDES, decryptByDES
      const message = JSON.parse(Crypto.decryptByDES(msg.data))
      console.log(message)
    }
  },
  modules: {}
})
